<?php
class Login extends CI_Controller
{

	public function Login(){
		parent::__construct();
		parse_str( $_SERVER['QUERY_STRING'], $_REQUEST );
		$CI = & get_instance();
		$CI->config->load("facebook",TRUE);
		$config = $CI->config->item('facebook');
		$this->load->library('Facebook', $config);
	}

	function index()
	{

		$this->form_validation->set_rules('username', 'Email', 'required|xss_clean|trim|valid_email|max_lenght[240]');
		$this->form_validation->set_rules('password', 'Password', 'required|trim');

		$user = $this->ion_auth->get_user();
		if($user){
			redirect("main");
		}

		$user = $this->facebook->getUser();
		$facebookFlag = false;

		if ($user) {
			
			try {
				$facebookuser = $this->facebook->api('/me');
				$facebookFlag = true;

				$username = $facebookuser['email'];

				if (!$this->ion_auth->username_check($username))
				{
					 
					$username = $facebookuser['email'];
					$password = 'temp123';
					$firstname = $facebookuser['first_name'];
					$lastname = $facebookuser['last_name'];
					 
					$email = $username;
					$additional_data = array(
							'first_name' => $firstname,
							'last_name' => $lastname,
					);
					 
					$group_name = 'members';

					$this->ion_auth->register($username, $password, $email, $additional_data, $group_name);
					 
					$ionuser = $this->ion_auth->get_user_by_username($username);
					 
					$this->ion_auth->activate($ionuser->id);
					 
					$session = $this->facebook->destroySession();
					$identity = $ionuser->username;
					$remember = TRUE; // remember the user
					$loggedIn = $this->ion_auth->loginNoPassword($identity, $remember);
					 
					$user = $this->ion_auth->get_user();
					
					redirect("main");
					
					return;
					 
				} else {
					 
					$ionuser = $this->ion_auth->get_user_by_username($username);
					 
					$identity = $ionuser->username;
					$remember = TRUE; // remember the user
					$loggedIn = $this->ion_auth->loginNoPassword($identity, $remember);
					 
					$session = $this->facebook->destroySession();
					 
					$user = $this->ion_auth->get_user();
					
					redirect("main");
						
					return;
				}

			} catch (FacebookApiException $e) {
				$user = null;
			}
		}
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['errors'] = null;
			$data['login_url'] = $this->facebook->getLoginUrl();
			$this->load->view('login_view', $data);
			return;
		}


		if($this->input->post('username')){

			$identity = $this->input->post('username');
			$password = $this->input->post('password');
			$remember = TRUE; // remember the user
			$loggedIn = $this->ion_auth->login($identity, $password, $remember);

			if(!$loggedIn){
				$data['errors']= $this->ion_auth->errors();
				$this->load->view('login_view',$data);
			} else {
				redirect("main");
			}

		} else {
			$data['errors'] = null;
			$this->load->view('login_view', $data);
		}
	}
}
?>